import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 50000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(function(config) {
  // 在发送请求之前做些什么
  // 给请求添加token
  const token = store.getters.token
  if (token && !config.url.includes('/register')) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
}, function(error) {
  // Do something with request error
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(function(response) {
  // Do something with response data
  // console.log('响应拦截器请求成功数据', response)
  const status = response.status
  // 成功
  if (status === 200) {
    return response
  } else {
    Message.success(response.statusText)
    return response
  }
}, function(error) {
  // Do something with response error
  // console.log('响应拦截器错误数据', error)
  Message.error(error.message)
  return Promise.reject(error)
})
export default service
